package example.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import util.SqlBuilder;
import util.StringUtil;

@Repository
public class EmpDao extends BaseDao{
	//需加入spring-tx-3.2.5.RELEASE.jar，否则报错The type org.springframework.dao.DataAccessException cannot be resolved
	//t means transaction
	//spring2.x没有这个包也不报错。。
	
	
	public List getAllList() {
		System.out.println("=== EmpDao: getAllList()");
		return this.jt.queryForList(" select * from emp ");
	}
	
	public List getEmpByEmpno(String empno) {
		System.out.println("=== EmpDao: getEmpById()");
		return jt.queryForList(" select * from emp where empno = ?", new Object[] { empno });
	}
	
	public int updateEmpByEmpnoException(Map params) {
		System.out.println("=== EmpDao: updateEmpByEmpnoException()");
		return jt.update(" update dept set ename = 'ename' where empno=? ");
	}
	
	public int updateEmpByEmpno(Map params) {
		System.out.println("=== EmpDao: updateEmpByEmpno()");
		return jt.update(" update emp set ename = '什么情况' where empno=123 ");
	}
	
	public int updateEmpByEmpno2(Map params) {
		System.out.println("=== EmpDao: updateEmpByEmpno2()");
		return jt.update(" update emp set ename = '两个service' where empno=3333 ");
	}
	
	public void updateEmpByEmpnoInnerException(Map params) {
		System.out.println("=== EmpDao: updateEmpByEmpnoInnerException()");
		jt.update(" update emp set ename = '内部事务执行正确' where empno=2222 ");
		System.out.println("=== EmpDao: updateEmpByEmpnoInnerException() —— 正确的执行完毕");
		jt.update(" update emp set dept = 'ename2222' where empno=? ");
	}
	
	
	public List searchEmp(Map params) {
		String ename = (null==params.get("ename")) ? null : params.get("ename").toString();
		
		String prefixSql = " select * from emp e ";
		String suffixSql = " order by e.empno ";
		
		SqlBuilder sb = new SqlBuilder(prefixSql, suffixSql);
		sb.addSqlString(" where 1=1 ");
		sb.addCondition(StringUtil.isNotBlank(ename), " ename = ? ", ename);
		String sql = sb.returnSql();
		Object[] args = sb.returnParams();
		System.out.println("生成的sql：" + sql);
		
		return jt.queryForList(sql, args);
	}
	
	public Map searchEmpPaging(Map params) {
		String ename = (null==params.get("ename")) ? null : params.get("ename").toString();
		
		String prefixSql = " select * from emp e where 1=1 ";
		String suffixSql = " order by e.empno ";
		
		SqlBuilder sb = new SqlBuilder(prefixSql, suffixSql);
		sb.addCondition(StringUtil.isNotBlank(ename), " ename = ? ", ename);
		String sql = sb.returnSql();
		Object[] args = sb.returnParams();
		
		Map<String, Object> pageParams = new HashMap<String, Object>();
		pageParams.put("pageNum", params.get("pageNum"));
		pageParams.put("pageSize", params.get("pageSize"));
		
		return this.pagingList(sql, args, pageParams);
	}
}
